from flask import Blueprint, request, jsonify
import json
from pathlib import Path
from typing import List, Dict, Any
from backend.app.utils.http import handle_request_error
from backend.app.config import CONFIG_DIR, CHARACTER_CONFIG_FILE

# 确保配置目录存在
Path(CONFIG_DIR).mkdir(exist_ok=True)

bp = Blueprint('character_config', __name__)


def load_character_config() -> List[Dict[str, Any]]:
    """加载角色配置"""
    try:
        if not Path(CHARACTER_CONFIG_FILE).exists():
            return []
        with open(CHARACTER_CONFIG_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading character config: {e}")
        return []


def save_character_config(characters: List[Dict[str, Any]]) -> bool:
    """保存角色配置"""
    try:
        with open(CHARACTER_CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(characters, f, indent=2, ensure_ascii=False)
        return True
    except Exception as e:
        print(f"Error saving character config: {e}")
        return False


@bp.route('/initCharacters', methods=['GET'])
@handle_request_error
def get_characters():
    """获取所有角色配置"""
    try:
        characters = load_character_config()
        return jsonify({
            "data": {
                "success": True,
                "characters": characters
            }
        })
    except Exception as e:
        return jsonify({
            "data": {
                "success": False,
                "error": str(e)
            }
        }), 500


@bp.route('/saveCharacter', methods=['POST'])
@handle_request_error
def save_characters():
    """保存角色配置"""
    try:
        data = request.json
        characters = data.get('characters', [])
        
        if save_character_config(characters):
            return jsonify({
                "data": {
                    "success": True,
                    "message": "保存角色配置成功"
                }
            })
        return jsonify({
            "data": {
                "success": False,
                "error": "保存失败"
            }
        }), 500
    except Exception as e:
        return jsonify({
            "data": {
                "success": False,
                "error": str(e)
            }
        }), 500


@bp.route('/delCharacter', methods=['POST'])
@handle_request_error
def delete_character():
    """删除指定角色"""
    try:
        data = request.json
        character_id = data.get('character_id')
        
        if not character_id:
            return jsonify({
                "data": {
                    "success": False,
                    "error": "缺少角色ID参数"
                }
            }), 400
            
        characters = load_character_config()
        characters = [c for c in characters if c.get("id") != character_id]
        
        if save_character_config(characters):
            return jsonify({
                "data": {
                    "success": True,
                    "message": "删除角色成功"
                }
            })
        return jsonify({
            "data": {
                "success": False,
                "error": "删除失败"
            }
        }), 500
    except Exception as e:
        return jsonify({
            "data": {
                "success": False,
                "error": str(e)
            }
        }), 500
